﻿#include "MyTcpClientThread.h"
#include "igbtprotocol.h"
#include "FrameDepacker.h"

MyTcpClientThread::MyTcpClientThread(FrameMgr* frameMgr, const QString& serverIP, unsigned int serverPort, QObject *parent)
    : TcpThread(new FrameDepacker(), serverIP, serverPort, parent)
{
	_frameMgr = frameMgr;
}

MyTcpClientThread::~MyTcpClientThread()
{
}

bool MyTcpClientThread::sendPacket()
{
    if (!TcpThread::sendPacket())
		return false;

    IGBTProtocol::BaseFrame* frame = _frameMgr->getOldestFrame();
	if (frame == NULL)
		return true;

    IGBTProtocol::CmdType cmdType = ((IGBTProtocol::CmdFrame*)frame)->cmdType();

	QByteArray buff;
    unsigned int size = frame->frame(&buff, true);

	int err;
    if (_tcpClient->send(buff.data(), size, &err) == -1)
	{
        emit stateChanged(FCMiddleware::ThreadStateType_WriteFailed, err, cmdType);
		delete frame;

		return false;
	}
	else
	{
        emit stateChanged(FCMiddleware::ThreadStateType_Quit + 1, 0, cmdType);
		delete frame;

		return true;
	}
}

bool MyTcpClientThread::recvPacket()
{
	QByteArray buff;
    if (_depacker->depack(&buff) == 0)
        return true;

    IGBTProtocol::FrameHeaderType frameHeaderType = IGBTProtocol::BaseFrame::judge(&buff);
    if(frameHeaderType == IGBTProtocol::FrameHeader_Cmd)
    {
        IGBTProtocol::CmdAckFrame* cmdAckFrame = new IGBTProtocol::CmdAckFrame();
        if(cmdAckFrame->depack(&buff))
            emit ackReady((void*)cmdAckFrame);
    }
    else if(frameHeaderType == IGBTProtocol::FrameHeader_Data)
    {
        IGBTProtocol::DataFrame* dataFrame = new IGBTProtocol::DataFrame();
        if(dataFrame->depack(&buff))
            emit ackReady((void*)dataFrame);
    }

	return true;
}
